//
//  ViewController.m
//  2.block实战
//
//  Created by CZ on 2020/11/23.
//  Copyright © 2020 CZ. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
// 其实和局部变量的声明是相同的,注意使用copy
@property (nonatomic, copy) NSString* (^appendStringBlock)(NSString *title);
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.声明局部变量
    [self declareABlock];
    
    // 2.作为属性
    self.appendStringBlock = ^NSString *(NSString *title) {
        return [NSString stringWithFormat:@"成员变量的block: %@", title];
    };
    
    NSLog(@"%@", self.appendStringBlock(@"张三"));
    
    // 3.作为参数
    [self declareAMethodWithBlock:^BOOL(NSInteger index) {
        return index < 10;
    }];
    
    // 4.递归调用
    [self recursiveBlock];
    
    // 5.作为返回值
    NSLog(@"%@", @([self returnBlockType](20)));
}

- (void)declareABlock {
    
    // 返回值类型+(^block名)(参数列表) = ^返回值类型(参数列表){...};
    NSInteger (^sumBlock)(NSInteger, NSInteger) = ^NSInteger (NSInteger a, NSInteger b) {
        return a + b;
    };
    
    NSInteger sum = sumBlock(1, 2);
    NSLog(@"sum = %@", @(sum));
}

- (void)declareAMethodWithBlock:(BOOL(^)(NSInteger index))callBackBlock {
    NSInteger idx = 0;
    while (callBackBlock(idx)) {
        NSLog(@"%@", @(idx));
        idx = idx + 1;
    }
}

- (void)recursiveBlock {
    __block NSInteger number = 0;
    __block void (^calculateSum) (NSInteger) = ^void (NSInteger input) {
        number = input + 1;
        if (number >= 10) {
            calculateSum = nil;
            return;
        }
        calculateSum(number);
    };
    
    calculateSum(1);
    NSLog(@"%@", @(number));
}

- (NSInteger (^) (NSInteger))returnBlockType {
    return ^ NSInteger (NSInteger a){
        return  a * a;
    };
}
@end

